package com.rory.gooday.memorial;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Page;
import com.rory.gooday.common.R;
import com.rory.gooday.common.model.Memorial;

import java.util.Calendar;

@Path("/memorial")
public class MemorialController extends Controller {
	
	@Inject
	MemorialService service;
	
	public void index() {
		render("memorial.html");
	}

	public void data() {
		Page<Memorial> a =  service.paginate(getParaToInt("page", 1), getParaToInt("limit", 10));
		renderJson(R.ok(a));
	}
	
	public void add() {
	}

	public void save() {
		String[] sendIntervalDayVals = getParaMap().get("sendIntervalDayVals[]");
		String sendIntervalDayValsStr = String.join(",", sendIntervalDayVals);
		String[] sendIntervalTimeVals = getParaMap().get("sendIntervalTimeVals[]");
		String sendIntervalTimeValsStr = String.join(",", sendIntervalTimeVals);
		Memorial memorial = getBean(Memorial.class);
		memorial.setSendIntervalDay(sendIntervalDayValsStr);
		memorial.setSendIntervalTime(sendIntervalTimeValsStr);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(memorial.getMemorialDayDate());
		memorial.setMemorialDayForYy(String.valueOf(calendar.get(Calendar.YEAR)));
		memorial.setMemorialDayForMm(String.valueOf(calendar.get(Calendar.MONTH) + 1));
		memorial.setMemorialDayForDd(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
		renderJson(R.ok(memorial.save()));
	}
	
	public void edit() {
		Memorial memorial = service.findById(getParaToInt());
		setAttr("memorial", memorial);
	}

	public void update() {
        String[] sendIntervalDayVals = getParaMap().get("sendIntervalDayVals[]");
        String sendIntervalDayValsStr = String.join(",", sendIntervalDayVals);
        String[] sendIntervalTimeVals = getParaMap().get("sendIntervalTimeVals[]");
        String sendIntervalTimeValsStr = String.join(",", sendIntervalTimeVals);
        Memorial memorial = getBean(Memorial.class);
        memorial.setSendIntervalDay(sendIntervalDayValsStr);
        memorial.setSendIntervalTime(sendIntervalTimeValsStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(memorial.getMemorialDayDate());
        memorial.setMemorialDayForYy(String.valueOf(calendar.get(Calendar.YEAR)));
        memorial.setMemorialDayForMm(String.valueOf(calendar.get(Calendar.MONTH) + 1));
        memorial.setMemorialDayForDd(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
        renderJson(R.ok(memorial.update()));
	}
	
	public void delete() {
		service.deleteById(getParaToInt());
		redirect("/memorial");
	}
}


